package com.example;

import java.util.UUID;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Conditional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import com.fasterxml.jackson.core.JsonProcessingException;

@SpringBootApplication
@RestController
@ComponentScan({"com.cmsz.xpay.framework.http.HttpClient","com.example"})
public class IpdemoApplication {
//	@Autowired
//	DeferredResultMiniCache deferredResultCache;
	@Value("${eshin.test}")
	String test;
	@Value("${project.basedir:123}")
	String name;
	@Value("${test.conf.pbe}")
	String confbase64;
	@Value("${test.conf}")
	String conf;
	
	
//	@Autowired
//	private RedisClient redisClient;
	
//	@Autowired
//	private  CacheAccessImpl cacheAccessImpl;
	@Autowired
	private HttpClient httpClient;
	@Value("${xpay.framework.test.pbe}")
	String base64;
	public static void main(String[] args) {
		SpringApplication.run(IpdemoApplication.class, args);
	}
	
	 @RequestMapping(value = "/getip", method = {RequestMethod.GET,RequestMethod.POST})
	    public String getip(HttpServletRequest request,@RequestParam String time) throws JsonProcessingException, InterruptedException {
	    	String ip = getClientID(request);
	    	int a = Integer.parseInt(time);
	    	System.out.println(a);
	    	Thread.sleep(a*1000L);
//	    	System.out.println(test);
	    	return ip;
	    }
	 @RequestMapping(value = "/norsp", method = {RequestMethod.GET,RequestMethod.POST})
	 public String getNorsp(HttpServletRequest request,@RequestParam String time) throws JsonProcessingException, InterruptedException {
		 String ip = getClientID(request);
		 int a = Integer.parseInt(time);
		 System.out.println(a);
//		 Thread.sleep(a*1000L);
//	    	System.out.println(test);
		 return ip;
	 }
	 @RequestMapping(value = "/testWeixin", method = {RequestMethod.GET,RequestMethod.POST})
	 public String getWeiXin(HttpServletRequest request) throws Exception {
		SSLContext context = SSLContext.getInstance("TLS");    
		context.init(null, null, null);    
		
		StringBuilder sb = new StringBuilder("");
		SSLSocketFactory factory = (SSLSocketFactory) context.getSocketFactory();    
		SSLSocket socket = (SSLSocket) factory.createSocket();    
		
		String[] protocols = socket.getSupportedProtocols();    
		sb.append("Supported Protocols: ");
		System.out.println("Supported Protocols: " + protocols.length+"..");    
		for (int i = 0; i < protocols.length; i++) {    
		    System.out.println(" " + protocols[i]);    
		    sb.append(" " + protocols[i]);
		}    
		
		protocols = socket.getEnabledProtocols();    
		sb.append("...Enabled Protocols: ");
		System.out.println("Enabled Protocols: " + protocols.length+"..");    
		for (int i = 0; i < protocols.length; i++) {    
		    System.out.println(" " + protocols[i]);
		    sb.append(" " + protocols[i]);
		}
		String mchId = "1350964201";
		String md5Key = "D5AC9FE5F90F4EDFA121FC9E3D19689D";
		String nonceStr = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
		String signStr = "mch_id="+mchId+"&nonce_str="+nonceStr+ "&key=" + md5Key;
		byte[] inputByteArr = signStr.getBytes("UTF-8");
		
		String sign = DigestUtils.md5Hex(inputByteArr).toUpperCase();
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xml>"
				+ "<mch_id>" + mchId + "</mch_id>"
				+ "<nonce_str>" + nonceStr + "</nonce_str>"
				+ "<sign>" + sign + "</sign>"
				+ "</xml>";
		String wxUrl  = "https://apitest.mch.weixin.qq.com/sandboxnew/pay/getsignkey";
		String rspXml = httpClient.sendStringMsg(wxUrl, xml);
		String data = "<xmp>"+ rspXml + "</xmp>";
		sb.append("...weixin response:"+data);
		return sb.toString();
	 }

	 @RequestMapping(value = "/test", method = RequestMethod.POST)
	 public DeferredResult<String> testDeferredResult(HttpServletRequest request,String test) throws InterruptedException{
		 DeferredResult<String> deferredResult = null;
		try {
//			 System.out.println(deferredResultCache.getResultMap().size());
			 deferredResult = new DeferredResult<>(10000L);
//			 Instant instant = Instant.now();
			 long key = System.nanoTime();
			 String keystr = ""+key;
//			 deferredResultCache.put(keystr, deferredResult);
//			 System.out.println(deferredResultCache.getResultMap().size());
			 
			 deferredResult.onTimeout(new Runnable() {
				
				@Override
				public void run() {
					System.out.println("test time out");
					throw new RuntimeException(" test exception in runable");
				}
			});
			 if("1".equals(test)){
				 Thread.sleep(11000L);
			 }
			 if("2".equals(test)){
				 deferredResult.setResult("i am test");
			 }
			 if("3".equals(test)){
				 throw new RuntimeException(" test exception");
			 }
//			 if("4".equals(test)){
//				 deferredResultCache.get(keystr).setResult("from cache result");
//			 }
			 if("5".equals(test)){
				 return null;
			 }
			 
//			 System.out.println(deferredResultCache.getResultMap().size());
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return deferredResult;
	 }
	    
	    private String getClientID(HttpServletRequest request) {
	        String ip = request.getHeader("x-forwarded-for");
	        String proxyip = request.getHeader("x-forwarded-for");
	        String proxyIP = request.getHeader("X-Forwarded-For");
	        String remoteIP = request.getRemoteAddr();
	        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
	            ip = request.getHeader("Proxy-Client-IP");
	        }
	        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
	            ip = request.getHeader("WL-Proxy-Client-IP");
	        }
	        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
	            ip = request.getRemoteAddr();
	        }

	        String ipStr = ip;
	        System.out.println(ip);
	        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
	        if (ip != null && ip.length() > 15) { //"***.***.***.***".length() = 15
	            if (ip.indexOf(",") > 0) {
	            	ip = ip.substring(0, ip.indexOf(","));
	            }
	        }
	        ip = "show ip if with proxy:"+ipStr+"; real ip:"+ip+"; proxy ip:"+proxyip+"; proxy IP:"+proxyIP+"; remote IP:"+remoteIP;
	        return ip;
	    }
	    @Bean
	    @Conditional(MyConditional.class)
	    public MyBean mybean(){
	    	MyBean mybean = new MyBean();
	    	mybean.setTest("eshin");
	    	System.out.println(conf+":"+confbase64);
	    	System.out.println("building mybean..."+base64);
			return mybean;
	    }
	    @Bean
	    @ConditionalOnProperty("eshin.test.hello")
	    public MyBean mybean2(){
	    	MyBean mybean = new MyBean();
	    	mybean.setTest("eshin");
	    	System.out.println("building mybean2..."+base64+name);
	    	return mybean;
	    }
	    @Bean
//	    @Conditional(MyConditional.class)
//	    @ConditionalOnMissingBean(MyBean.class)
	    @ConditionalOnProperty(value = "eshin.test.second.enabled", matchIfMissing = true)
	    public MyBean mybean1(){
	    	MyBean mybean = new MyBean();
	    	mybean.setTest("eshin");
	    	System.out.println("building when missing mybean...");
	    	return mybean;
	    }
}
